package com.yiyi.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

/**
 * Redis 频道工具类
 *
 * @author yiyi
 * @date 2021/6/6
 */
public class JedisUtil {
    public static void publishMsg(String channel, String message) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        try {
            jedis.publish(channel, message);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            jedis.close();
        }
    }

    public static JedisPubSub jedisPubSub = new JedisPubSub() {
        @Override
        public void onMessage(String channel, String message) {
            System.out.println("收到了" + channel + "频道发来消息：" +  message);
            System.out.println(channel + ":" + message);
        }

        @Override
        public void onSubscribe(String channel, int subscribedChannels) {
            System.out.println("订阅了" + channel + "频道");
            System.out.println(channel + ":" + subscribedChannels);
        }

        @Override
        public void onUnsubscribe(String channel, int subscribedChannels) {
            System.out.println("取消订阅了" + channel + "频道");
            System.out.println(channel + ":" + subscribedChannels);
        }
    };

    /**
     * 接收消息。
     * 该方法调用后，会一直执行下去。当有发布对应消息时，就会在jedisPubSub中接收到！
     *
     * @param channels
     */
    public static void subscribeMsg(String channels) {
        // Jedis jedis = getJedis();
        Jedis jedis = new Jedis ("127.0.0.1", 6379);
        new Thread(()->{
            try {
                jedis.subscribe(jedisPubSub, channels);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                // jedis.close();
            }
        }).start();
    }
}
